import express from 'express'
import cors from 'cors'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import multer from 'multer'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const app = express()
const PORT = 3002  // 后端API服务器端口（两个前端项目共用）

// 订单数据文件路径
const ORDERS_FILE = path.join(__dirname, 'orders.json')
// 用户数据文件路径
const USERS_FILE = path.join(__dirname, 'users.json')

// 上传文件目录
const UPLOADS_DIR = path.join(__dirname, 'uploads')
const AVATARS_DIR = path.join(UPLOADS_DIR, 'avatars')

// 确保上传目录存在
if (!fs.existsSync(UPLOADS_DIR)) {
  fs.mkdirSync(UPLOADS_DIR, { recursive: true })
}
if (!fs.existsSync(AVATARS_DIR)) {
  fs.mkdirSync(AVATARS_DIR, { recursive: true })
}

app.use(cors())
app.use(express.json())

// 配置静态文件服务，让前端可以访问上传的图片
app.use('/uploads', express.static(UPLOADS_DIR))

// ========== 内存数据库（示例） ==========
const products = [
  // 美妆
  { id: 1, name: '保湿面膜', category: 'makeup', price: 89, image: 'https://picsum.photos/200?random=1', description: '深层补水，滋养肌肤' },
  { id: 2, name: '口红套装', category: 'makeup', price: 199, image: 'https://picsum.photos/200?random=2', description: '多色可选，持久不脱色' },
  { id: 3, name: '洁面乳', category: 'makeup', price: 69, image: 'https://picsum.photos/200?random=3', description: '温和清洁，不紧绷' },
  { id: 19, name: 'NARS大白饼', category: 'makeup', price: 399, image: 'https://images.unsplash.com/photo-1522337360788-8b13dee7a37e?w=400', description: 'NARS 定妆粉饼，透明无痕，长效控油' },

  // 服饰
  { id: 4, name: '春季连衣裙', category: 'clothing', price: 299, image: 'https://picsum.photos/200?random=4', description: '时尚百搭，舒适面料' },
  { id: 5, name: '休闲T恤', category: 'clothing', price: 79, image: 'https://picsum.photos/200?random=5', description: '纯棉材质，透气舒适' },
  { id: 6, name: '牛仔裤', category: 'clothing', price: 159, image: 'https://picsum.photos/200?random=6', description: '经典款式，修身剪裁' },

  // 数码
  { id: 7, name: '蓝牙耳机', category: 'digital', price: 399, image: 'https://picsum.photos/200?random=7', description: '降噪功能，续航持久' },
  { id: 8, name: '智能手表', category: 'digital', price: 1299, image: 'https://picsum.photos/200?random=8', description: '健康监测，运动追踪' },
  { id: 9, name: '移动电源', category: 'digital', price: 99, image: 'https://picsum.photos/200?random=9', description: '大容量，快充技术' },

  // 电器
  { id: 10, name: '电饭煲', category: 'appliance', price: 299, image: 'https://picsum.photos/200?random=10', description: '智能预约，24小时保温' },
  { id: 11, name: '空气净化器', category: 'appliance', price: 899, image: 'https://picsum.photos/200?random=11', description: '高效过滤，静音运行' },
  { id: 12, name: '榨汁机', category: 'appliance', price: 199, image: 'https://picsum.photos/200?random=12', description: '一键操作，易清洗' },

  // 生鲜
  { id: 13, name: '新鲜苹果', category: 'fresh', price: 29.9, image: 'https://picsum.photos/200?random=13', description: '脆甜多汁，产地直供' },
  { id: 14, name: '有机蔬菜', category: 'fresh', price: 19.9, image: 'https://picsum.photos/200?random=14', description: '绿色无公害，营养丰富' },
  { id: 15, name: '进口牛肉', category: 'fresh', price: 159, image: 'https://picsum.photos/200?random=15', description: '精选部位，新鲜配送' },

  // 户外
  { id: 16, name: '登山杖', category: 'outdoor', price: 149, image: 'https://picsum.photos/200?random=16', description: '轻便耐用，防滑设计' },
  { id: 17, name: '帐篷', category: 'outdoor', price: 599, image: 'https://picsum.photos/200?random=17', description: '防风防雨，易搭建' },
  { id: 18, name: '露营灯', category: 'outdoor', price: 89, image: 'https://picsum.photos/200?random=18', description: 'LED灯珠，长续航' }
]

// ========== 用户数据存储 ==========
// 从文件读取用户数据（如果文件存在）
let users = []
function loadUsers() {
  try {
    if (fs.existsSync(USERS_FILE)) {
      const data = fs.readFileSync(USERS_FILE, 'utf8')
      users = JSON.parse(data)
      console.log(`✅ 从文件加载了 ${users.length} 个用户`)
    } else {
      // 如果文件不存在，使用默认用户数据
      users = [
        { id: 1, username: 'admin', password: '123456', email: 'admin@example.com', role: 'admin', avatar: '', nickname: 'admin', updatedAt: new Date().toISOString() },
        { id: 2, username: 'test', password: '123456', email: 'test@example.com', role: 'user', avatar: '', nickname: 'test', updatedAt: new Date().toISOString() }
      ]
      // 保存默认用户数据到文件
      saveUsers()
      console.log('📝 用户文件不存在，已创建默认用户数据')
    }
  } catch (error) {
    console.error('❌ 读取用户文件失败:', error)
    // 如果读取失败，使用默认用户数据
    users = [
      { id: 1, username: 'admin', password: '123456', email: 'admin@example.com', role: 'admin', avatar: '', nickname: 'admin', updatedAt: new Date().toISOString() },
      { id: 2, username: 'test', password: '123456', email: 'test@example.com', role: 'user', avatar: '', nickname: 'test', updatedAt: new Date().toISOString() }
    ]
  }
}

// 保存用户数据到文件
function saveUsers() {
  try {
    fs.writeFileSync(USERS_FILE, JSON.stringify(users, null, 2), 'utf8')
    console.log(`💾 用户数据已保存到文件 (共 ${users.length} 个用户)`)
  } catch (error) {
    console.error('❌ 保存用户文件失败:', error)
  }
}

// 启动时加载用户数据
loadUsers()

// 简易 token 存储，映射到用户（演示用途）
const tokenStore = new Map() // token -> { id, username, email, role, avatar, nickname }

// ========== 公共接口 ==========
app.get('/api/products/hot', (req, res) => {
  const hotProductIds = [19, 1, 4, 7, 10, 2, 16, 13]
  const hotProducts = hotProductIds.map(id => products.find(p => p.id === id)).filter(Boolean)
  res.json(hotProducts.slice(0, 8))
})

app.get('/api/products', (req, res) => {
  const { category } = req.query
  let filtered = products
  if (category && category !== 'all') {
    filtered = products.filter(p => p.category === category)
  }
  res.json(filtered)
})

app.get('/api/products/:id', (req, res) => {
  const { id } = req.params
  const product = products.find(p => p.id === parseInt(id))
  if (!product) return res.status(404).json({ message: '商品未找到' })
  res.json(product)
})

// 统计信息接口
app.get('/api/stats', (req, res) => {
  // 计算商品分类统计
  const categoryStats = {}
  products.forEach(product => {
    if (!categoryStats[product.category]) {
      categoryStats[product.category] = 0
    }
    categoryStats[product.category]++
  })
  
  // 计算总库存价值
  const totalValue = products.reduce((sum, p) => sum + (p.price || 0), 0)
  
  res.json({
    success: true,
    data: {
      totalProducts: products.length,
      totalValue: totalValue,
      categoryStats: categoryStats
    }
  })
})

app.post('/api/cart', (req, res) => {
  const { productId } = req.body
  const product = products.find(p => p.id === productId)
  if (!product) return res.status(404).json({ message: '商品未找到' })
  res.json({ message: '已添加到购物车', product })
})

app.get('/api/search', (req, res) => {
  const { keyword } = req.query
  if (!keyword) return res.json([])
  const kw = String(keyword).toLowerCase()
  const results = products.filter(p =>
      p.name.toLowerCase().includes(kw) ||
      (p.description || '').toLowerCase().includes(kw)
  )
  res.json(results)
})

// ========== 用户注册 / 登录 ==========
app.post('/api/register', (req, res) => {
  const { username, password, email } = req.body
  if (!username || !password || !email) {
    return res.json({ success: false, message: '请填写完整信息' })
  }
  if (users.find(u => u.username === username)) {
    return res.json({ success: false, message: '用户名已存在' })
  }
  if (users.find(u => u.email === email)) {
    return res.json({ success: false, message: '邮箱已被注册' })
  }

  const newUser = {
    id: users.length + 1,
    username,
    password, // 生产需加密
    email,
    role: 'user',
    avatar: '',
    nickname: username,
    updatedAt: new Date().toISOString()
  }
  users.push(newUser)
  // 保存用户数据到文件
  saveUsers()
  return res.json({
    success: true,
    message: '注册成功',
    user: { id: newUser.id, username: newUser.username, email: newUser.email, role: newUser.role, avatar: newUser.avatar, nickname: newUser.nickname }
  })
})

app.post('/api/login', (req, res) => {
  const { username, password } = req.body
  if (!username || !password) {
    return res.json({ success: false, message: '请输入用户名和密码' })
  }
  // 使用字符串比较确保类型一致
  const user = users.find(u => u.username === username && String(u.password) === String(password))
  if (!user) {
    return res.json({ success: false, message: '用户名或密码错误' })
  }
  const token = `token_${Date.now()}_${user.id}`
  const userInfo = { 
    id: user.id, 
    username: user.username, 
    email: user.email, 
    role: user.role,
    avatar: user.avatar || '',
    nickname: user.nickname || user.username
  }
  tokenStore.set(token, userInfo)
  return res.json({
    success: true,
    message: '登录成功',
    token,
    user: userInfo
  })
})

// ========== 鉴权中间件 ==========
function authGuard(req, res, next) {
  const auth = req.headers.authorization || ''
  const [scheme, token] = auth.split(' ')
  console.log('🔐 认证检查:', req.method, req.url, 'Token存在:', !!token)
  if (scheme !== 'Bearer' || !token) {
    console.log('❌ 认证失败: 缺少Token')
    return res.status(401).json({ success: false, message: '未授权' })
  }
  const payload = tokenStore.get(token)
  if (!payload) {
    console.log('❌ 认证失败: Token无效或过期')
    console.log('   当前Token存储:', Array.from(tokenStore.keys()).slice(0, 3))
    return res.status(401).json({ success: false, message: '无效或过期的 token' })
  }
  console.log('✅ 认证成功: 用户', payload.username)
  req.user = payload
  next()
}

function adminGuard(req, res, next) {
  console.log('👮 权限检查: 用户角色', req.user?.role)
  if (!req.user || req.user.role !== 'admin') {
    console.log('❌ 权限不足: 需要管理员权限')
    return res.status(403).json({ success: false, message: '无权限访问' })
  }
  console.log('✅ 权限验证通过')
  next()
}

// ========== 管理员登录与后台接口 ==========
app.post('/api/admin/login', (req, res) => {
  const { username, password } = req.body
  if (!username || !password) {
    return res.json({ success: false, message: '请输入用户名和密码' })
  }
  
  // 先查找用户（使用字符串比较确保类型一致）
  const user = users.find(u => u.username === username && String(u.password) === String(password))
  
  // 如果用户不存在或密码错误
  if (!user) {
    return res.json({ success: false, message: '用户名或密码错误' })
  }
  
  // 如果用户存在但不是管理员
  if (user.role !== 'admin') {
    return res.json({ success: false, message: '无法登录，请使用管理员账户' })
  }
  
  // 管理员登录成功
  const token = `admin_${Date.now()}_${user.id}`
  const userInfo = { 
    id: user.id, 
    username: user.username, 
    email: user.email, 
    role: user.role,
    avatar: user.avatar || '',
    nickname: user.nickname || user.username
  }
  tokenStore.set(token, userInfo)
  return res.json({
    success: true,
    message: '管理员登录成功',
    token,
    user: userInfo
  })
})

// ========== 文件上传配置 ==========
// 配置multer存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, AVATARS_DIR)
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名：用户ID_时间戳_原文件名
    const userId = req.user?.id || 'unknown'
    const timestamp = Date.now()
    const ext = path.extname(file.originalname)
    const filename = `${userId}_${timestamp}${ext}`
    cb(null, filename)
  }
})

// 文件过滤器：只允许图片文件
const fileFilter = (req, file, cb) => {
  const allowedTypes = /jpeg|jpg|png|gif|webp/
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase())
  const mimetype = allowedTypes.test(file.mimetype)
  
  if (extname && mimetype) {
    cb(null, true)
  } else {
    cb(new Error('只允许上传图片文件（jpeg, jpg, png, gif, webp）'))
  }
}

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制文件大小为5MB
  },
  fileFilter: fileFilter
})

// ========== 用户信息接口 ==========
// 上传头像
app.post('/api/user/avatar', authGuard, upload.single('avatar'), (req, res) => {
  if (!req.file) {
    return res.json({ success: false, message: '请选择要上传的文件' })
  }
  
  // 生成图片URL（相对于静态文件服务路径，存储时使用相对路径）
  const avatarUrl = `/uploads/avatars/${req.file.filename}`
  
  // 更新用户的头像URL
  const user = users.find(u => u.id === req.user.id)
  if (user) {
    // 如果用户有旧头像，删除旧文件
    if (user.avatar) {
      let oldAvatarPath
      // 处理完整URL或相对路径
      if (user.avatar.startsWith('http://localhost:') || user.avatar.startsWith('http://')) {
        // 如果是完整URL，提取路径部分
        const urlObj = new URL(user.avatar)
        oldAvatarPath = path.join(__dirname, urlObj.pathname)
      } else if (user.avatar.startsWith('/uploads/avatars/')) {
        // 如果是相对路径
        oldAvatarPath = path.join(__dirname, user.avatar)
      }
      
      if (oldAvatarPath && fs.existsSync(oldAvatarPath)) {
        try {
          fs.unlinkSync(oldAvatarPath)
          console.log('✅ 已删除旧头像文件:', oldAvatarPath)
        } catch (error) {
          console.error('❌ 删除旧头像失败:', error)
        }
      }
    }
    
    // 保存相对路径到用户数据
    user.avatar = avatarUrl
    user.updatedAt = new Date().toISOString()
    
    // 保存用户数据到文件（持久化）
    saveUsers()
    
    // 更新tokenStore中的用户信息（使用相对路径，前端通过代理访问）
    const token = req.headers.authorization?.split(' ')[1]
    if (token && tokenStore.has(token)) {
      const tokenUserInfo = tokenStore.get(token)
      tokenStore.set(token, {
        ...tokenUserInfo,
        avatar: avatarUrl
      })
    }
  }
  
  // 返回相对路径的头像URL（前端通过Vite代理访问）
  res.json({
    success: true,
    message: '头像上传成功',
    data: {
      avatarUrl: avatarUrl,
      filename: req.file.filename
    }
  })
})

// 获取当前用户信息
app.get('/api/user/profile', authGuard, (req, res) => {
  const user = users.find(u => u.id === req.user.id)
  if (!user) {
    return res.status(404).json({ success: false, message: '用户不存在' })
  }
  
  // 返回用户信息（不包含密码）
  // 如果头像是本地上传的（相对路径），前端会通过代理访问
  // 如果是外部URL，直接返回
  let avatarUrl = user.avatar || ''
  
  const userInfo = {
    id: user.id,
    username: user.username,
    email: user.email,
    role: user.role,
    avatar: avatarUrl,
    nickname: user.nickname || user.username,
    updatedAt: user.updatedAt
  }
  
  res.json({ success: true, data: userInfo })
})

// 更新当前用户信息
app.put('/api/user/profile', authGuard, (req, res) => {
  const { avatar, nickname, email, username, oldPassword, newPassword } = req.body
  const user = users.find(u => u.id === req.user.id)
  if (!user) {
    return res.status(404).json({ success: false, message: '用户不存在' })
  }
  
  // 更新允许修改的字段
  if (avatar !== undefined) {
    user.avatar = avatar
  }
  if (nickname !== undefined && nickname.trim()) {
    user.nickname = nickname.trim()
  }
  if (email !== undefined && email.trim()) {
    // 检查邮箱是否已被其他用户使用
    const emailExists = users.find(u => u.id !== user.id && u.email === email.trim())
    if (emailExists) {
      return res.json({ success: false, message: '邮箱已被使用' })
    }
    user.email = email.trim()
  }
  // 修改用户名
  if (username !== undefined && username.trim()) {
    const newUsername = username.trim()
    // 用户名相同则忽略
    if (newUsername !== user.username) {
      // 检查用户名是否被占用
      const usernameExists = users.find(u => u.username === newUsername)
      if (usernameExists) {
        return res.json({ success: false, message: '用户名已存在' })
      }
      user.username = newUsername
    }
  }
  // 修改密码：需要提供 oldPassword 和 newPassword
  if (oldPassword !== undefined || newPassword !== undefined) {
    if (!oldPassword || !newPassword) {
      return res.json({ success: false, message: '修改密码需要提供旧密码与新密码' })
    }
    // 确保密码比较时类型一致（都转为字符串比较）
    const currentPassword = String(user.password)
    const providedOldPassword = String(oldPassword)
    if (providedOldPassword !== currentPassword) {
      console.log(`❌ 密码验证失败: 用户 ${user.username}, 提供的旧密码: ${providedOldPassword}, 存储的密码: ${currentPassword}`)
      return res.json({ success: false, message: '旧密码不正确' })
    }
    if (String(newPassword).length < 6) {
      return res.json({ success: false, message: '新密码长度不能少于6位' })
    }
    user.password = String(newPassword)
    console.log(`✅ 用户 ${user.username} 的密码已更新`)
  }
  
  user.updatedAt = new Date().toISOString()
  
  // 保存用户数据到文件（持久化）- 重要！这样密码更改才会被保存
  saveUsers()
  console.log(`💾 用户 ${user.username} 的信息已保存到文件`)
  
  // 更新tokenStore中的用户信息
  const token = req.headers.authorization?.split(' ')[1]
  if (token && tokenStore.has(token)) {
    const tokenUserInfo = tokenStore.get(token)
    tokenStore.set(token, {
      ...tokenUserInfo,
      username: user.username, // 更新用户名（如果修改了）
      avatar: user.avatar || '',
      nickname: user.nickname || user.username,
      email: user.email
    })
  }
  
  // 返回更新后的用户信息（不包含密码）
  const userInfo = {
    id: user.id,
    username: user.username,
    email: user.email,
    role: user.role,
    avatar: user.avatar || '',
    nickname: user.nickname || user.username,
    updatedAt: user.updatedAt
  }
  
  res.json({ success: true, message: '更新成功', data: userInfo })
})

// 仪表盘统计
app.get('/api/admin/dashboard', authGuard, adminGuard, (req, res) => {
  // 计算订单统计
  const orderStats = {
    totalOrders: orders.length,
    pendingOrders: orders.filter(o => o.status === 'pending').length,
    processingOrders: orders.filter(o => o.status === 'processing').length,
    completedOrders: orders.filter(o => o.status === 'completed').length,
    shippedOrders: orders.filter(o => o.status === 'shipped').length,
    cancelledOrders: orders.filter(o => o.status === 'cancelled').length,
    totalRevenue: orders
      .filter(o => o.status === 'completed')
      .reduce((sum, o) => sum + (o.totalPrice || 0), 0)
  }
  
  // 计算商品分类统计
  const categoryStats = {}
  products.forEach(product => {
    if (!categoryStats[product.category]) {
      categoryStats[product.category] = 0
    }
    categoryStats[product.category]++
  })
  
  // 计算总库存价值
  const totalValue = products.reduce((sum, p) => sum + (p.price || 0), 0)
  
  return res.json({
    success: true,
    data: {
      totalUsers: users.length,
      totalProducts: products.length,
      totalValue: totalValue,
      categoryStats: categoryStats,
      orderStats: orderStats,
      hotProducts: [19, 1, 4, 7].length
    }
  })
})

// 商品管理 CRUD（示例）
app.get('/api/admin/products', authGuard, adminGuard, (req, res) => {
  res.json({ success: true, data: products })
})

app.post('/api/admin/products', authGuard, adminGuard, (req, res) => {
  const { name, category, price, image, description } = req.body
  if (!name || !category || typeof price !== 'number') {
    return res.json({ success: false, message: '缺少必要字段' })
  }
  const id = Math.max(...products.map(p => p.id)) + 1
  const newProduct = { id, name, category, price, image: image || '', description: description || '' }
  products.push(newProduct)
  res.json({ success: true, data: newProduct })
})

app.put('/api/admin/products/:id', authGuard, adminGuard, (req, res) => {
  const { id } = req.params
  const idx = products.findIndex(p => p.id === parseInt(id))
  if (idx === -1) return res.status(404).json({ success: false, message: '商品未找到' })
  const { name, category, price, image, description } = req.body
  products[idx] = {
    ...products[idx],
    name: name ?? products[idx].name,
    category: category ?? products[idx].category,
    price: typeof price === 'number' ? price : products[idx].price,
    image: image ?? products[idx].image,
    description: description ?? products[idx].description
  }
  res.json({ success: true, data: products[idx] })
})

app.delete('/api/admin/products/:id', authGuard, adminGuard, (req, res) => {
  const { id } = req.params
  const idx = products.findIndex(p => p.id === parseInt(id))
  if (idx === -1) return res.status(404).json({ success: false, message: '商品未找到' })
  const removed = products.splice(idx, 1)[0]
  res.json({ success: true, data: removed })
})
// ========== 订单数据存储 ==========
// 从文件读取订单数据（如果文件存在）
let orders = []
function loadOrders() {
  try {
    if (fs.existsSync(ORDERS_FILE)) {
      const data = fs.readFileSync(ORDERS_FILE, 'utf8')
      orders = JSON.parse(data)
      console.log(`✅ 从文件加载了 ${orders.length} 个订单`)
    } else {
      orders = []
      console.log('📝 订单文件不存在，使用空订单列表')
    }
  } catch (error) {
    console.error('❌ 读取订单文件失败:', error)
    orders = []
  }
}

// 保存订单数据到文件
function saveOrders() {
  try {
    fs.writeFileSync(ORDERS_FILE, JSON.stringify(orders, null, 2), 'utf8')
    console.log(`💾 订单数据已保存到文件 (共 ${orders.length} 个订单)`)
  } catch (error) {
    console.error('❌ 保存订单文件失败:', error)
  }
}

// 启动时加载订单数据
loadOrders()

// ========== 订单相关接口 ==========

// 测试路由 - 检查服务器是否正常运行
app.get('/api/test', (req, res) => {
  res.json({ success: true, message: '后台服务器运行正常', timestamp: new Date().toISOString() })
})

// 1. 创建订单（购物网站下单时调用）
app.post('/api/orders', authGuard, (req, res) => {
  console.log('收到订单创建请求:', {
    method: req.method,
    url: req.url,
    body: req.body,
    headers: req.headers.authorization ? '有token' : '无token'
  })
  
  const { items, shippingAddress, totalPrice } = req.body

  // items: [{ productId, name, price, quantity }]
  // shippingAddress: { name, phone, address, city, province }

  if (!items || !Array.isArray(items) || items.length === 0) {
    return res.json({ success: false, message: '订单商品不能为空' })
  }
  if (!shippingAddress || !shippingAddress.name || !shippingAddress.phone || !shippingAddress.address) {
    return res.json({ success: false, message: '收货信息不完整' })
  }

  const newOrder = {
    id: 'ORD' + Date.now(), // 使用字符串格式，便于前台项目使用
    userId: req.user.id,
    username: req.user.username,
    items: items,
    shippingAddress: shippingAddress,
    totalPrice: totalPrice || items.reduce((sum, item) => sum + item.price * item.quantity, 0),
    status: 'pending', // pending:待处理, processing:处理中, shipped:已发货, completed:已完成, cancelled:已取消
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }

  orders.push(newOrder)
  console.log('订单创建成功:', newOrder.id, '当前订单总数:', orders.length)
  // 保存到文件
  saveOrders()
  res.json({ success: true, data: newOrder, message: '订单创建成功' })
})

// 2. 获取订单列表（管理员查看所有订单）
app.get('/api/admin/orders', authGuard, adminGuard, (req, res) => {
  console.log('✅ 收到获取订单列表请求')
  console.log('   请求用户:', req.user.username, '角色:', req.user.role)
  console.log('   当前订单数:', orders.length)
  console.log('   订单ID列表:', orders.map(o => o.id))
  res.json({ success: true, data: orders })
})

// 3. 获取单个订单详情（用户和管理员都可以访问）
app.get('/api/orders/:id', authGuard, (req, res) => {
  console.log('收到订单查询请求:', req.params.id, '当前订单数:', orders.length)
  console.log('所有订单ID:', orders.map(o => o.id))
  
  // 支持字符串ID和数字ID查找
  const order = orders.find(o => {
    const match = o.id === req.params.id || o.id === parseInt(req.params.id)
    if (match) console.log('找到订单:', o.id, '用户ID:', o.userId, '请求用户ID:', req.user.id)
    return match
  })
  
  if (!order) {
    console.log('订单未找到:', req.params.id)
    return res.status(404).json({ success: false, message: '订单不存在' })
  }
  
  // 普通用户只能查看自己的订单，管理员可以查看所有订单
  if (req.user.role !== 'admin' && order.userId !== req.user.id) {
    console.log('权限不足:', order.userId, '!==', req.user.id)
    return res.status(403).json({ success: false, message: '无权访问此订单' })
  }
  
  console.log('返回订单数据:', order.id)
  res.json({ success: true, data: order })
})

// 管理员获取单个订单详情（保留原有接口）
app.get('/api/admin/orders/:id', authGuard, adminGuard, (req, res) => {
  // 支持字符串ID和数字ID查找
  const order = orders.find(o => o.id === req.params.id || o.id === parseInt(req.params.id))
  if (!order) {
    return res.status(404).json({ success: false, message: '订单不存在' })
  }
  res.json({ success: true, data: order })
})

// 4. 更新订单状态（管理员处理订单）
app.put('/api/admin/orders/:id/status', authGuard, adminGuard, (req, res) => {
  const { status } = req.body
  // 支持字符串ID和数字ID查找
  const order = orders.find(o => o.id === req.params.id || o.id === parseInt(req.params.id))
  if (!order) {
    return res.status(404).json({ success: false, message: '订单不存在' })
  }

  const validStatuses = ['pending', 'processing', 'shipped', 'completed', 'cancelled']
  if (!validStatuses.includes(status)) {
    return res.json({ success: false, message: '无效的订单状态' })
  }

  order.status = status
  order.updatedAt = new Date().toISOString()
  // 保存到文件
  saveOrders()
  res.json({ success: true, data: order, message: '订单状态更新成功' })
})

// 5. 批量更新订单状态
app.post('/api/admin/orders/batch-update', authGuard, adminGuard, (req, res) => {
  const { orderIds, status } = req.body
  
  if (!orderIds || !Array.isArray(orderIds) || orderIds.length === 0) {
    return res.json({ success: false, message: '请选择要更新的订单' })
  }
  
  if (!status) {
    return res.json({ success: false, message: '请指定订单状态' })
  }
  
  const validStatuses = ['pending', 'processing', 'shipped', 'completed', 'cancelled']
  if (!validStatuses.includes(status)) {
    return res.json({ success: false, message: '无效的订单状态' })
  }
  
  const updatedOrders = []
  const notFoundIds = []
  
  orderIds.forEach(orderId => {
    const order = orders.find(o => o.id === orderId || o.id === parseInt(orderId))
    if (order) {
      order.status = status
      order.updatedAt = new Date().toISOString()
      updatedOrders.push(order)
    } else {
      notFoundIds.push(orderId)
    }
  })
  
  if (updatedOrders.length > 0) {
    saveOrders()
  }
  
  res.json({
    success: true,
    message: `成功更新 ${updatedOrders.length} 个订单`,
    data: {
      updated: updatedOrders.length,
      orders: updatedOrders,
      notFound: notFoundIds
    }
  })
})

// 6. 图表数据API
app.get('/api/admin/dashboard/charts', authGuard, adminGuard, (req, res) => {
  const { startDate, endDate, type } = req.query
  
  // 默认时间范围：最近30天
  const now = new Date()
  const defaultStartDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
  
  const start = startDate ? new Date(startDate) : defaultStartDate
  const end = endDate ? new Date(endDate) : now
  
  // 过滤时间范围内的订单
  const filteredOrders = orders.filter(order => {
    const orderDate = new Date(order.createdAt || order.updatedAt)
    return orderDate >= start && orderDate <= end
  })
  
  // 1. 订单趋势数据（按日期统计）
  const orderTrend = {}
  filteredOrders.forEach(order => {
    const date = new Date(order.createdAt).toISOString().split('T')[0]
    if (!orderTrend[date]) {
      orderTrend[date] = { date, count: 0, revenue: 0 }
    }
    orderTrend[date].count++
    if (order.status === 'completed') {
      orderTrend[date].revenue += order.totalPrice || 0
    }
  })
  
  const orderTrendData = Object.values(orderTrend).sort((a, b) => 
    new Date(a.date) - new Date(b.date)
  )
  
  // 2. 销售分布数据（按分类统计）
  const salesByCategory = {}
  filteredOrders.forEach(order => {
    order.items?.forEach(item => {
      const product = products.find(p => p.id === item.productId)
      if (product) {
        const category = product.category
        if (!salesByCategory[category]) {
          salesByCategory[category] = { category, count: 0, revenue: 0 }
        }
        salesByCategory[category].count += item.quantity
        if (order.status === 'completed') {
          salesByCategory[category].revenue += item.price * item.quantity
        }
      }
    })
  })
  
  // 3. 订单状态统计
  const statusStats = {
    pending: filteredOrders.filter(o => o.status === 'pending').length,
    processing: filteredOrders.filter(o => o.status === 'processing').length,
    shipped: filteredOrders.filter(o => o.status === 'shipped').length,
    completed: filteredOrders.filter(o => o.status === 'completed').length,
    cancelled: filteredOrders.filter(o => o.status === 'cancelled').length
  }
  
  // 4. 最近24小时实时数据
  const last24Hours = new Date(now.getTime() - 24 * 60 * 60 * 1000)
  const recentOrders = orders.filter(order => {
    const orderDate = new Date(order.createdAt)
    return orderDate >= last24Hours
  })
  
  const realtimeStats = {
    ordersCount: recentOrders.length,
    revenue: recentOrders
      .filter(o => o.status === 'completed')
      .reduce((sum, o) => sum + (o.totalPrice || 0), 0),
    hourlyData: {}
  }
  
  // 按小时统计最近24小时
  for (let i = 23; i >= 0; i--) {
    const hourStart = new Date(now.getTime() - i * 60 * 60 * 1000)
    const hourEnd = new Date(now.getTime() - (i - 1) * 60 * 60 * 1000)
    const hourKey = hourStart.getHours().toString().padStart(2, '0') + ':00'
    
    const hourOrders = recentOrders.filter(order => {
      const orderDate = new Date(order.createdAt)
      return orderDate >= hourStart && orderDate < hourEnd
    })
    
    realtimeStats.hourlyData[hourKey] = {
      count: hourOrders.length,
      revenue: hourOrders
        .filter(o => o.status === 'completed')
        .reduce((sum, o) => sum + (o.totalPrice || 0), 0)
    }
  }
  
  // 根据type返回不同的数据
  const responseData = {
    orderTrend: orderTrendData,
    salesDistribution: Object.values(salesByCategory),
    statusStats: statusStats,
    realtimeStats: realtimeStats
  }
  
  if (type && responseData[type]) {
    res.json({ success: true, data: { [type]: responseData[type] } })
  } else {
    res.json({ success: true, data: responseData })
  }
})
// 404处理 - 所有未匹配的路由
app.use((req, res) => {
  console.log('❌ 404 - 未找到路由:', req.method, req.url)
  res.status(404).json({ 
    success: false, 
    message: `路由未找到: ${req.method} ${req.url}`,
    availableRoutes: [
      'POST /api/login',
      'POST /api/register',
      'POST /api/orders',
      'GET /api/orders/:id',
      'GET /api/products',
      'GET /api/test'
    ]
  })
})

app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`)
  console.log(`📋 可用路由:`)
  console.log(`   POST /api/login - 用户登录`)
  console.log(`   POST /api/register - 用户注册`)
  console.log(`   POST /api/admin/login - 管理员登录`)
  console.log(`   POST /api/orders - 创建订单`)
  console.log(`   GET /api/orders/:id - 获取订单详情`)
  console.log(`   GET /api/admin/orders - 获取所有订单（管理员）`)
  console.log(`   PUT /api/admin/orders/:id/status - 更新订单状态（管理员）`)
  console.log(`   POST /api/admin/orders/batch-update - 批量更新订单状态（管理员）`)
  console.log(`   GET /api/products - 获取商品列表`)
  console.log(`   GET /api/stats - 获取统计信息`)
  console.log(`   GET /api/admin/dashboard - 获取仪表盘数据（管理员）`)
  console.log(`   GET /api/admin/dashboard/charts - 获取图表数据（管理员）`)
  console.log(`   GET /api/user/profile - 获取用户信息（需要认证）`)
  console.log(`   PUT /api/user/profile - 更新用户信息（需要认证）`)
  console.log(`   POST /api/user/avatar - 上传头像（需要认证）`)
  console.log(`   GET /api/test - 测试服务器`)
})